<template>
  <div>
    <input type="text" v-model="searchQuery" placeholder="搜索节点" />
    <div ref="knowledgeGraph" style="height: 500px;"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import axios from 'axios';
import cytoscape from 'cytoscape';
import panzoom from 'cytoscape-panzoom';

const knowledgeGraph = ref(null);
const searchQuery = ref('');
const cy = ref(null);

//确保 panzoom 插件已正确加载
if (typeof cytoscape('core', 'panzoom') !== 'function') {
  panzoom(cytoscape);
}

onMounted(async () => {
  try {
    //从后端获取数据
    const response = await axios.get('http://localhost:8000/qa/knowledge-graph/');
    const data = response.data;

    //初始化 cytoscape 图谱
    cy.value = cytoscape({
      container: knowledgeGraph.value,
      elements: transformData(data),
      style: [
        {
          selector: 'node',
          style: {
            'background-color': 'green', //将节点背景色设置为绿色
            'label': 'data(label)',
            'width': '40',
            'height': '40',
            'shape': 'ellipse',
            'color': 'black' // 将节点字体颜色设置为黑色
          }
        },
        {
          selector: 'node[description="无描述"]',
          style: {
            'background-color': 'lightgreen' //无描述的节点背景色设置为浅绿色
          }
        },
        {
          selector: 'edge',
          style: {
            'width': 1.5,
            'line-color': '#ccc',
            'target-arrow-color': '#ccc',
            'target-arrow-shape': 'triangle'
          }
        },
        {
          selector: 'edge[relationshipType="景区简介"]',
          style: {
            'line-style': 'dashed'
          }
        }
      ],
      layout: {
        name: 'cose', //使用 cose 布局算法
        padding: 10 //节点之间的间距
      }
    });

    // 添加 panzoom 功能
    cy.value.panzoom({
      minZoom: 0.1,
      maxZoom: 10,
      zoomFactor: 0.05
    });
  } catch (error) {
    console.error('获取知识图谱失败:', error);
  }
});

// 数据转换函数
function transformData(rawData) {
  const elements = {
    nodes: [],
    edges: []
  };

  rawData.forEach(item => {
    const start = item.p.start;
    const end = item.p.end;
    const relationshipType = item.p.segments[0].relationship.type;

    // 添加起点节点
    elements.nodes.push({
      data: {
        id: start.elementId,
        label: start.properties.name,
        type: start.labels[0],
        description: start.properties.description || "无描述"
      }
    });

    // 添加终点节点
    elements.nodes.push({
      data: {
        id: end.elementId,
        label: end.properties.name,
        type: end.labels[0],
        description: end.properties.description || "无描述"
      }
    });

    // 添加边
    elements.edges.push({
      data: {
        id: item.p.segments[0].relationship.elementId,
        source: start.elementId,
        target: end.elementId,
        type: relationshipType,
        relationshipType: relationshipType // 添加关系类型属性
      }
    });
  });

  const uniqueNodes = new Map(elements.nodes.map(node => [node.data.id, node]));
  elements.nodes = Array.from(uniqueNodes.values());

  return elements;
}

watch(searchQuery, (newQuery) => {
  if (!cy.value) return;
  const nodes = cy.value.elements('node');
  const query = newQuery.toLowerCase().trim();

  nodes.forEach((node) => {
    const label = node.data('label').toLowerCase();
    const visible = label.includes(query) || query === '';
    node.style('visibility', visible ? 'visible' : 'hidden');
    node.style('opacity', visible ? 1 : 0);
  });

  cy.value.fit();
});
</script>
<style>
#knowledge-graph {
  width: 100%;
}
</style>
